#include "AnimatorHolder.h"
#include <algorithm>

std::list<Animator*> AnimatorHolder::running, AnimatorHolder::suspended, AnimatorHolder::pending_suspention;
std::list<Animator*> AnimatorHolder::paused;
timestamp_t AnimatorHolder::pauseTime;

void AnimatorHolder::Register(Animator* a) { suspended.push_back(a); }
	
void AnimatorHolder::Cancel(Animator* a) { suspended.remove(a); }

void AnimatorHolder::MarkAsRunning(Animator* a) { 
	suspended.remove(a);
	running.push_back(a); 
}

void AnimatorHolder::MarkAsSuspended(Animator* a) { 
	running.remove(a);
	suspended.push_back(a); 
}

void AnimatorHolder::MarkAsPaused(Animator* a) { 
	running.remove(a);
	paused.push_back(a);
}

void AnimatorHolder::MarkAsResumed(Animator* a) { 
	paused.remove(a);
	running.push_back(a); 
}

void AnimatorHolder::DelayedSuspention(Animator *a) {
	pending_suspention.push_back(a);
}

void AnimatorHolder::Progress(timestamp_t currTime) {
//	printf("size=%d\n", running.size());

	std::for_each(running.begin(), running.end(), ProgressFunctor(currTime));
	std::list<Animator *>::iterator i;
	for(i=pending_suspention.begin(); i != pending_suspention.end(); i++)
		MarkAsSuspended(*i);

	pending_suspention.clear();
}

void AnimatorHolder::Pause(void) {
	pauseTime = Timer::getsystime();

	std::list<Animator *>::iterator it;
//	printf("size of running list = %d\n", running.size());
	
	for(it=running.begin(); it!=running.end(); ++it) {
		paused.push_back(*it);
	}
	running.clear();
}

void AnimatorHolder::Resume(void) {
	timestamp_t pauseOffset = (Timer::getsystime()-pauseTime);

	std::list<Animator*>::iterator it;
	for(it=paused.begin(); it!=paused.end(); ++it) {
		(*it)->TimeShift(pauseOffset);
		running.push_back(*it);
	}

	paused.clear();
}